package com.seng.resourcetycoon.util;

import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Random;

public class Util {

    private final static Random random = new Random();

    /**
     * 从集合中随机选择一个元素。
     * @param collection 集合
     * @param <T> 集合元素类型
     * @return 随机选择的元素
     */
    public static <T> T getRandomElement(Collection<T> collection) {
        if (collection == null || collection.isEmpty()) {
           return null;
        }
        int randomIndex = random.nextInt(collection.size());
        Iterator<T> iterator = collection.iterator();
        for (int i = 0; i <= randomIndex; i++) {
            if (!iterator.hasNext()) {
                // 如果因为并发修改导致的异常，这里可能需要重新获取迭代器或处理逻辑
                throw new ConcurrentModificationException();
            }
            if (i == randomIndex) {
                return iterator.next();
            } else {
                iterator.next();
            }
        }
        return null; //理论上不会到达这里
    }

    public static <T> T improvedRandomElementOrDefault(Collection<T> collection, T defaultVal) {
        if (collection == null || collection.isEmpty()) {
            return defaultVal;
        }
        int randomIndex = random.nextInt(collection.size());
        Iterator<T> iterator = collection.iterator();
        for (int i = 0; i <= randomIndex; i++) {
            if (!iterator.hasNext()) {
                // 如果因为并发修改导致的异常，这里可能需要重新获取迭代器或处理逻辑
                throw new ConcurrentModificationException();
            }
            if (i == randomIndex) {
                return iterator.next();
            } else {
                iterator.next();
            }
        }
        return defaultVal; //理论上不会到达这里
    }
}
